#!/usr/bin/perl -w

use strict;

die "usage:perl $0 <gene.family.info.xls> <out.name> <fill or no-fill> \n" unless @ARGV == 3;

open OUT,">cmd.r";
print OUT "
theta= seq(0,2*pi,pi/1000)
inf=read.table(\"$ARGV[0]\",header=T)
pdf(file=\"venn.$ARGV[1].pdf\",w=10,h=10)
test=inf


aa=nrow(test) 
bb=ncol(test)
r=1;a=4;b=2;
n=64
require(graphics)
library(scales)

mycol <- c(34, 51, 142, 26, 31, 371, 36, 7, 12, 30, 84, 88, 116, 121, 77, 56, 386, 373, 423, 435, 438, 471, 512, 130, 52, 47, 6, 11, 43, 54, 367, 382, 422, 4, 8, 375, 124, 448, 419, 614, 401, 403, 613, 583, 652, 628, 633, 496, 638, 655, 132, 503, 24)
mycol <-colors()[rep(mycol,20)]
color = mycol



#color=rainbow(n, s = 1, v = 1, start = 0, end = max(1, n - 1)/n, alpha = 1) 
row=nrow(color)
column=ncol(color)
space=seq(0,2*pi,length=aa+1);
rota=seq(0,360,length=aa+1);
for (i in 1:aa){
x0=cos(space[i])*(a-r);
y0=sin(space[i])*(a-r);
alpha=space[i];
text_x1=(2*a-1+1)*cos(space[i]);
text_y1=(2*a-1+1)*sin(space[i]);
text_x2=(2*a-2)*cos(space[i]);
text_y2=(2*a-2)*sin(space[i]);
text_xx1=(2*a-1+0.5)*cos(space[i]);
	text_yy1=(2*a-1+0.5)*sin(space[i]);
	text_xx2=(2*a-1.5)*cos(space[i]);
	text_yy2=(2*a-1.5)*sin(space[i]);
	marker1=test[i,1];
	marker2=test[i,3];
	x3=x0+a*cos(alpha)*cos(theta)-b*sin(alpha)*sin(theta);
	y3=y0+a*sin(alpha)*cos(theta)+b*cos(alpha)*sin(theta);
	par(new=T)
";	
	if ($ARGV[2] eq "fill"){
	print OUT "
	plot(x3,y3,type=\"l\",xlim=c(-8,8),ylim=c(-8,8),lwd=2,axes=F,xlab=\"\",ylab=\"\")
	#polygon(x3,y3,col = rgb(255, 0, 0, 20, maxColorValue=255))
	polygon(x3,y3,col = alpha(color[i],0.45))
	";
	}else{
	print OUT "
	col=rainbow(n)
	plot(x3,y3,type=\"l\",xlim=c(-8,8),ylim=c(-8,8),col=col[i],lwd=2,axes=F,xlab=\"\",ylab=\"\")	
	;"
	}
print OUT "
	name=paste(\"n=\",test[i,4])
	if (rota[i] <= 180){
		text(text_x1,text_y1,labels=marker1,srt=(rota[i]-90),xpd=F,cex=1,font=0.5)
		text(text_xx1,text_yy1,labels=name,srt=(rota[i]-90),xpd=T,cex=1,font=0.5)
		text(text_x2,text_y2,labels=marker2,srt=(rota[i]-90),xpd=T,cex=1,font=0.5);
		}else{
		text(text_x1,text_y1,labels=marker1,srt=(rota[i]+90),xpd=T,cex=1,font=0.5)
		text(text_xx1,text_yy1,labels=name,srt=(rota[i]+90),xpd=T,cex=1,font=0.5)
		text(text_x2,text_y2,labels=marker2,srt=(rota[i]+90),xpd=T,cex=1,font=0.5);
			}
		}
x=cos(theta);y=sin(theta);
lines(x,y,type=\"l\",col=\"black\")
text(0,0,labels=test[1,2],xpd=T,cex=1,font=1);
dev.off()
";
`R --restore --no-save < cmd.r`;

